//
//  DocumentBuilder.m
//  iFlickr
//
//  Created by 张 霄鹤 on 09-7-5.
//  Copyright 2009 xhzhang. All rights reserved.
//

#import "DocumentBuilder.h"
#import "Element.h"
#import "TextNode.h"

@implementation DocumentBuilder

/**
 * 快捷方法，创建 DocumentBuilder
 */
+(id)makeDocumentBuilder{
	return [[[DocumentBuilder alloc] init] autorelease];
}

/**
 * 初始化
 */
- (id)init{
	if(self = [super init]){
		level = [[Stack alloc] init];
	}
	return self;
}

- (Document *)parseWithString:(NSString *)xml{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	NSData *data = [xml dataUsingEncoding:NSUTF8StringEncoding];
	BOOL bOK = [self parseWithData:data];
	Document *ret = nil;
	
	if(bOK){
		ret = parseResult;
	}
	[pool release];
	
	return ret;
}

- (BOOL)parseWithData:(NSData *)data{
	BOOL bret = NO;
	if(data && [data length] > 0){
		NSXMLParser *saxParser = [[NSXMLParser alloc] initWithData:data];
		[saxParser setDelegate:self];
		[saxParser setShouldProcessNamespaces:NO];
		bret = [saxParser parse];
		[saxParser release];
	}
	return bret;
}

#pragma mark -
#pragma mark NSXMLParserDelegate

- (void)parserDidStartDocument:(NSXMLParser *)parser{
	// TODO 文档开始
	if(parseResult){
		[parseResult autorelease];
		parseResult = nil;
	}
	parseResult = [[Document alloc] init];
	[level removeAll];
	[level push:parseResult];
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName
	attributes:(NSDictionary *)attributeDict{	
//#ifdef DEBUG
//	NSLog(@"Element: %@",elementName);
//#endif
	Element *element = [level peek];
	Element *nElement = [[Element alloc] initWithName:elementName];
	[nElement setAttributes:attributeDict];
	[element appendChild:nElement];
	[level push:nElement];
	[nElement release];
}

/**
 * 处理文本内容，文本内容不用进入 level
 */
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
	//NSInteger sl = [string length];
//	if(sl == 0){
//		return;
//	}
	// TODO text
	id nd = [level peek];
	if([nd isKindOfClass:[TextNode class]]){
//#ifdef DEBUG
//		NSLog(@"Append Text: %@",string);
//#endif
		TextNode *text = (TextNode *)nd;
		[text appendText:string];
	}else{
		
//#ifdef DEBUG
//		NSLog(@"Create Text: %@",string);
//#endif
		Element *element = (Element *)nd;
		TextNode *textNode = [[TextNode alloc] initWithText:string];
		[element appendChild:textNode];
		[textNode release];
	}
}

- (void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString{
	
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
  namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{
	// TODO 标签结束
	[level pop];
}

- (void)parserDidEndDocument:(NSXMLParser *)parser{
	// TODO 文档结束
	[level removeAll];
//#ifdef DEBUG
//	NSLog(@"END Doc");
//#endif
}

#pragma mark -
#pragma mark Memory Manage dealloc
-(void)dealloc{
	[level removeAll];
	[level release];
	[parseResult release];
	[super dealloc];
}

@end
